#define _CRT_SECURE_NO_WARNINGS
#include"List.h"
//创建节点:
ListNode* BuyNode(LTDatatype x)
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	if (node == NULL)
	{
		perror("malloc");
		exit(1);
	}
	node->val = x;
	node->next = node;
	node->prev = node;
	return node;
}

//初始化（创建头节点）
void LTInit(ListNode** pphead)
{
	//创建节点:
	*pphead = BuyNode(-1);
}

//尾插
void LTPushBack(ListNode* phead, LTDatatype x)
{
	assert(phead);
	ListNode* newnode = BuyNode(x);
	newnode->next = phead;
	newnode->prev = phead->prev;

	phead->prev->next = newnode;
	phead->prev = newnode;
}

//打印:
void LTPrint(ListNode* phead)
{
	phead = phead->next;
	while (phead->val != -1)
	{
		printf("%d->", phead->val);
		phead = phead->next;
	}
	printf("\n");
}

//头插:
void LTPushFront(ListNode* phead, LTDatatype x)
{
	assert(phead);
	ListNode* newnode = BuyNode(x);
	newnode->prev = phead;
	newnode->next = phead->next;

	phead->next->prev = newnode;
	phead->next = newnode;
}

//尾删:
void LTPopBack(ListNode* phead)
{
	assert(phead->next!=phead&&phead);
	phead->prev = phead->prev->prev;
	phead->prev->next->next = phead->prev->next->prev = NULL;
	free(phead->prev->next);
	phead->prev->next = phead;
}

//头删:
void LTPopFront(ListNode* phead)
{
	assert(phead->next!=NULL&&phead);
	phead->next = phead->next->next;
	phead->next->prev->next = phead->next->prev->prev=NULL;
	free(phead->next->prev);
	phead->next->prev = phead;
}

//在指定位置之后插入数据:
void LTInsertAfter(ListNode* phead, int pos, LTDatatype x)
{
	assert(phead&&pos>=0);
	ListNode* cur = phead;
	while (pos--)
	{
		cur = cur->next;
	}
	ListNode* newnode = BuyNode(x);
	newnode->prev = cur;
	newnode->next = cur->next;
	cur->next = newnode;
	newnode->next->prev = newnode;
}

//在指定位置之前插入数据
void LTInsertBefore(ListNode* phead, int pos, LTDatatype x)
{
	assert(phead&&pos>=1);
	ListNode* cur = phead;
	while (pos-1)
	{
		cur = cur->next;
		pos--;
	}
	ListNode* newnode = BuyNode(x);
	newnode->prev = cur;
	newnode->next = cur->next;
	cur->next = newnode;
	newnode->next->prev = newnode;
}

//查找:
ListNode* LTFind(ListNode* phead, LTDatatype x)
{
	assert(phead && phead->next != phead);
	phead = phead->next;
	while (phead->next != phead)
	{
		if (phead->val == x)
		{
			return phead;
		}
		phead = phead->next;
	}
	return NULL;
}

//删除指定位置节点:
//pos的位置不能为哨兵位！！！！！！！！！
void LTErase(ListNode* phead, int pos)
{
	assert(phead && phead->next != phead&&pos>=1);
	ListNode* cur = phead;
	while (pos--)
		cur = cur->next;
	cur->prev->next = cur->next;
	cur->next->prev = cur->prev;
	cur->next = cur->prev = NULL;
	free(cur);
}

//销毁:
void LTDestroy(ListNode** pphead)
{
	ListNode* cur = (*pphead)->next;
	while (cur != *pphead)
	{
		ListNode* nxt = cur->next;
		free(cur);
		cur = nxt;
	}
	free(cur);
	*pphead = NULL;
}